﻿namespace USElections.TwitterLibrary.Converters
{
    using System;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using TweetSharp;
    using USElections.TwitterLibrary.Commands;

    /// <summary>
    /// TweetStatusConverter class.
    /// </summary>
    public class TweetStatusConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            TwitterStatus status = value as TwitterStatus;

            RichTextBox rtb = new RichTextBox();

            if (status != null)
            {
                int pos = 0;

                Paragraph para = new Paragraph();

                while (pos < status.Text.Length)
                {
                    foreach (var entity in status.Entities)
                    {
                        para.Inlines.Add(new Run() { Text = status.Text.Substring(pos, entity.StartIndex - pos) });

                        pos = entity.StartIndex;

                        TwitterMention mention = entity as TwitterMention;
                        TwitterUrl url = entity as TwitterUrl;

                        if (mention != null)
                        {
                            para.Inlines.Add(new Run() { Text = status.Text.Substring(pos, entity.EndIndex - pos) });
                        }
                        else if (url != null)
                        {
                            Hyperlink hp = new Hyperlink();
                            hp.Inlines.Add(url.Value); // status.Text.Substring(pos, entity.EndIndex - pos);
                            hp.Command = new OpenWebBrowserCommand();
                            hp.CommandParameter = url.Value; 

                            para.Inlines.Add(hp);
                        }
                        else
                        {
                            para.Inlines.Add(new Run() { Text = status.Text.Substring(pos, entity.EndIndex - pos) });
                        }

                        pos = entity.EndIndex;
                    }

                    if (pos != status.Text.Length)
                    {
                        para.Inlines.Add(new Run() { Text = status.Text.Substring(pos, status.Text.Length - pos) });

                        pos = status.Text.Length;
                    }
                }

                rtb.Blocks.Add(para);
            }

            return rtb;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
